package ngram.reader;

import exceptions.NegativeNumberException;
import exceptions.NegativeNumberOrZeroException;
import ngram.util.IOUtil;
import java.io.DataInputStream;
import java.io.EOFException;
import java.io.IOException;

/**
 * Readers custom n-gram file version 1, where: <br />
 * year = short (2 bytes) <br />
 * volume count = int (4 bytes) <br />
 * match count = int (4 bytes) <br />
 * 
 * @author g1wshimu
 */
public class V1FileReader implements NGramFileReader {

    private final DataInputStream STREAM;

    public V1FileReader(DataInputStream stream) {
        this.STREAM = stream;
    }

    /**
     * 
     * @param reader
     * @return null if the end of file (EOF) is reached.
     * @throws NegativeNumberException if the length of the String is less than 0
     */
    @Override
    public String readNGram() throws IOException, NegativeNumberException {
        return IOUtil.readUtf(STREAM);
    }

    @Override
    public int readYear() throws IOException {
        return STREAM.readShort();
    }

    @Override
    public long readVolumeCount() throws IOException {
        return STREAM.readInt();
    }

    @Override
    public long readMatchCount() throws IOException {
        return STREAM.readInt();
    }

    public int readHeader() throws IOException,
            NegativeNumberOrZeroException {
        short header = STREAM.readShort();
        NegativeNumberOrZeroException.validate("header", header);
        return header;
    }

    public void skip(int lines) throws IOException {
        // Number of bytes to skip 
        // = year + matchCount + volumeCount
        // = short + int + int
        // = 2 + 4 + 4 (bytes)
        // = 10 (bytes)

        IOUtil.skip(STREAM, 10 * lines);
    }

}
